import shutil
import pandas as pd
from pathlib import Path
from PySide6.QtCore import Qt, Signal, QThread
from .file_handing import FileHanding


class FileTidingThread(QThread):
    """文件整理线程"""
    _infoChangedSignal = Signal(object)
    _stateChangedSignal = Signal()
    _notFoundSignal = Signal(list)
    _finishedSignal = Signal()

    def __init__(self, data:dict, parent=None):
        super().__init__(parent=parent)
        self.src_dir:Path = data["src_dir"]
        self.dst_dir:Path = data["dst_dir"]
        self.df:pd.DataFrame = data["df"]
    
    def copy_file(self, index, source, destName):
        if self.pre_copy_emit(index):
            suffix = Path(source).suffix
            self.dst_dir.mkdir(parents=True, exist_ok=True)
            new_file_path = self.dst_dir / f'{destName}{suffix}' # make sure is valid path
            shutil.copy2(source, new_file_path)
            self.post_copy_emit(index)
    
    def pre_copy_emit(self, index):
        if self.df.at[index, '处理状态'] == "已重命名并保存":
            return False
        self.df.at[index, '处理状态'] = "处理中"
        self._infoChangedSignal.emit(self.df)
        return True

    def post_copy_emit(self, index):
        self.df.at[index, '处理状态'] = "已重命名并保存"
        self._infoChangedSignal.emit(self.df)

    def not_exit_emit(self, index, ):
        self.df.at[index, '处理状态'] = "未找到文件"
        self._infoChangedSignal.emit(self.df)
        

    def search_and_save(self):
        not_found_files = []
        self._stateChangedSignal.emit()
        columns = self.df.columns.tolist()
        columns.remove('处理状态')

        for index, row in self.df.iterrows():
            sku_filename = row[columns[1]]
            file_path = FileHanding.search_file(self.src_dir, sku_filename)

            if file_path:
                # destFileName = f"{row[columns[0]]}-{row[columns[1]]}-{row[columns[2]]}"
                # destFilaName = "-".join(columns)
                destFileName = "-".join(row[columns[i]] for i in range(len(columns)))
                print('destFileName:', destFileName)
                self.copy_file(index, file_path, destFileName)
            else:
                self.not_exit_emit(index)
                not_found_files.append(sku_filename)
        
        self._stateChangedSignal.emit()
        self._finishedSignal.emit()
        
        if not_found_files:
            self._notFoundSignal.emit(not_found_files)


    # def search_and_save(self):
    #     not_found_files = []
    #     self._stateChangedSignal.emit()
    #     columns = self.df.columns.tolist()

    #     for index, row in self.df.iterrows():
    #         sku_filename = row[columns[1]]
    #         file_path = FileHanding.search_file(self.src_dir, sku_filename)

    #         if file_path:
    #             # if self.df.at[index, '处理状态'] == "已重命名并保存":
    #             #     continue

    #             # self.df.at[index, '处理状态'] = "处理中"
    #             # self._infoChangedSignal.emit(self.df)

    #             destFileName = f"{row[columns[0]]}-{row[columns[1]]}-{row[columns[2]]}"
    #             self.copy_file(file_path, destFileName)
    
    #             # file_suffix = Path(file_path).suffix
    #             # new_filename = f"{row[columns[0]]}-{row[columns[1]]}-{row[columns[2]]}.{file_suffix}"
    #             # self.dst_dir.mkdir(parents=True, exist_ok=True)
    #             # new_file_path = self.dst_dir / new_filename
    #             # shutil.copy2(file_path, new_file_path)

    #             # self.df.at[index, '处理状态'] = "已重命名并保存"
    #             # self._infoChangedSignal.emit(self.df)
    #             # print(f"文件已复制到 {new_file_path}")
            
    #         else:
    #             self.df.at[index, '处理状态'] = "未找到文件"
    #             self._infoChangedSignal.emit(self.df)
    #             not_found_files.append(sku_filename)
        
    #     self._stateChangedSignal.emit()
    #     self._finishedSignal.emit()
        
    #     if not_found_files:
    #         self._notFoundSignal.emit(not_found_files)

    def run(self):
        self.search_and_save()

